import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseHelper {
  static const _databaseName = "moonmate.db";
  static const _databaseVersion = 2; // 升级数据库版本以支持新功能

  // 表名定义
  static const tableUser = 'user';
  static const tableUserSettings = 'user_settings'; // 新增用户设置表
  static const tablePeriod = 'period';
  static const tableSymptom = 'symptom';
  static const tableOvulation = 'ovulation';
  static const tablePregnancy = 'pregnancy';
  static const tablePregnancyCheckup = 'pregnancy_checkup';
  static const tableBabyGrowth = 'baby_growth';
  static const tableVaccine = 'vaccine';
  static const tableFoodSafety = 'food_safety';
  static const tableKnowledge = 'knowledge';
  static const tablePhoto = 'photo';
  // 新增表名 - 支持跨模式数据管理
  static const tableBBTRecords = 'bbt_records';
  static const tableCMRecords = 'cm_records';
  static const tableOvulationTests = 'ovulation_tests';
  static const tableFetalMovements = 'fetal_movements';
  static const tableBabyInfo = 'baby_info';
  static const tableFeedingRecords = 'feeding_records';
  static const tableSleepRecords = 'sleep_records';

  // 列名定义 - 用户表
  static const columnUserId = '_id';
  static const columnUserName = 'name';
  static const columnUserEmail = 'email'; // 新增邮箱字段
  static const columnUserPasswordHash = 'password_hash'; // 新增密码哈希字段
  static const columnUserAvatar = 'avatar';
  static const columnUserPhone = 'phone_number'; // 新增手机号字段
  static const columnUserDOB = 'date_of_birth'; // 新增出生日期字段
  static const columnUserHeight = 'height'; // 新增身高字段
  static const columnUserWeight = 'weight'; // 新增体重字段
  static const columnUserBloodType = 'blood_type'; // 新增血型字段
  static const columnUserMode = 'current_mode';
  static const columnUserCycle = 'avg_cycle_days';
  static const columnUserPeriod = 'avg_period_days';
  static const columnUserCreatedAt = 'created_at'; // 新增创建时间字段
  static const columnUserLastLogin = 'last_login'; // 新增最后登录时间字段
  
  // 列名定义 - 用户设置表
  static const columnSettingsId = '_id';
  static const columnSettingsUserId = 'user_id';
  static const columnSettingsKey = 'setting_key';
  static const columnSettingsValue = 'setting_value';

  // 列名定义 - 经期表
  static const columnPeriodId = '_id';
  static const columnPeriodStart = 'start_date';
  static const columnPeriodEnd = 'end_date';
  static const columnPeriodFlow = 'flow_intensity';
  static const columnPeriodNote = 'note';
  static const columnPeriodUserId = 'user_id';

  // 列名定义 - 症状表
  static const columnSymptomId = '_id';
  static const columnSymptomName = 'symptom_name';
  static const columnSymptomSeverity = 'severity';
  static const columnSymptomDate = 'symptom_date';
  static const columnSymptomPeriodId = 'period_id';

  // 私有构造函数
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // 数据库实例
  static Database? _database;

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  // 关闭数据库连接
  Future<void> close() async {
    if (_database != null) {
      await _database!.close();
      _database = null;
      debugPrint('数据库已关闭');
    }
  }

  // 重新打开数据库连接
  Future<void> reopen() async {
    if (_database != null) {
      await _database!.close();
    }
    _database = await _initDatabase();
    debugPrint('数据库已重新打开');
  }

  // 初始化数据库
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path, version: _databaseVersion, onCreate: _onCreate);
  }

  // 创建数据库表
  Future _onCreate(Database db, int version) async {
    // 创建用户表
    await db.execute('''
          CREATE TABLE $tableUser (
            $columnUserId INTEGER PRIMARY KEY AUTOINCREMENT,
            $columnUserName TEXT NOT NULL,
            $columnUserEmail TEXT UNIQUE,
            $columnUserPasswordHash TEXT,
            $columnUserAvatar TEXT,
            $columnUserPhone TEXT,
            $columnUserDOB TEXT,
            $columnUserHeight INTEGER,
            $columnUserWeight INTEGER,
            $columnUserBloodType TEXT,
            $columnUserMode TEXT NOT NULL DEFAULT 'period',
            $columnUserCycle INTEGER DEFAULT 28,
            $columnUserPeriod INTEGER DEFAULT 5,
            $columnUserCreatedAt TEXT NOT NULL,
            $columnUserLastLogin TEXT NOT NULL
          )
          ''');
          
    // 创建用户设置表
    await db.execute('''
          CREATE TABLE $tableUserSettings (
            $columnSettingsId INTEGER PRIMARY KEY AUTOINCREMENT,
            $columnSettingsUserId INTEGER NOT NULL,
            $columnSettingsKey TEXT NOT NULL,
            $columnSettingsValue TEXT NOT NULL,
            FOREIGN KEY ($columnSettingsUserId) REFERENCES $tableUser ($columnUserId) ON DELETE CASCADE,
            UNIQUE ($columnSettingsUserId, $columnSettingsKey)
          )
          ''');
          
    // 创建基础体温记录表（备孕模式）
    await db.execute('''
          CREATE TABLE $tableBBTRecords (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            record_date TEXT NOT NULL,
            temperature REAL NOT NULL,
            notes TEXT,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId) ON DELETE CASCADE
          )
          ''');
          
    // 创建宫颈粘液记录表（备孕模式）
    await db.execute('''
          CREATE TABLE $tableCMRecords (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            record_date TEXT NOT NULL,
            cm_type TEXT NOT NULL,
            amount INTEGER,
            notes TEXT,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId) ON DELETE CASCADE
          )
          ''');
          
    // 创建排卵测试记录表（备孕模式）
    await db.execute('''
          CREATE TABLE $tableOvulationTests (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            test_date TEXT NOT NULL,
            result INTEGER NOT NULL,
            test_image_path TEXT,
            notes TEXT,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId) ON DELETE CASCADE
          )
          ''');
          
    // 创建胎动记录表（孕期模式）
    await db.execute('''
          CREATE TABLE $tableFetalMovements (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            pregnancy_id INTEGER NOT NULL,
            record_date TEXT NOT NULL,
            record_time TEXT NOT NULL,
            movement_count INTEGER NOT NULL,
            notes TEXT,
            FOREIGN KEY (pregnancy_id) REFERENCES $tablePregnancy (_id) ON DELETE CASCADE
          )
          ''');
          
    // 创建宝宝信息表（育儿模式）
    await db.execute('''
          CREATE TABLE $tableBabyInfo (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            name TEXT NOT NULL,
            gender TEXT,
            birth_date TEXT NOT NULL,
            birth_weight REAL,
            birth_height REAL,
            delivery_method TEXT,
            notes TEXT,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId) ON DELETE CASCADE
          )
          ''');
          
    // 创建喂养记录表（育儿模式）
    await db.execute('''
          CREATE TABLE $tableFeedingRecords (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            baby_id INTEGER NOT NULL,
            record_date TEXT NOT NULL,
            record_time TEXT NOT NULL,
            feeding_type TEXT NOT NULL,
            duration INTEGER,
            amount REAL,
            breast_side TEXT,
            notes TEXT,
            FOREIGN KEY (baby_id) REFERENCES $tableBabyInfo (_id) ON DELETE CASCADE
          )
          ''');
          
    // 创建睡眠记录表（育儿模式）
    await db.execute('''
          CREATE TABLE $tableSleepRecords (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            baby_id INTEGER NOT NULL,
            start_date TEXT NOT NULL,
            start_time TEXT NOT NULL,
            end_date TEXT NOT NULL,
            end_time TEXT NOT NULL,
            quality INTEGER,
            notes TEXT,
            FOREIGN KEY (baby_id) REFERENCES $tableBabyInfo (_id) ON DELETE CASCADE
          )
          ''');
          

    // 创建经期表
    await db.execute('''
          CREATE TABLE $tablePeriod (
            $columnPeriodId INTEGER PRIMARY KEY AUTOINCREMENT,
            $columnPeriodStart TEXT NOT NULL,
            $columnPeriodEnd TEXT NOT NULL,
            $columnPeriodFlow INTEGER,
            $columnPeriodNote TEXT,
            $columnPeriodUserId INTEGER NOT NULL,
            FOREIGN KEY ($columnPeriodUserId) REFERENCES $tableUser ($columnUserId)
          )
          ''');

    // 创建症状表
    await db.execute('''
          CREATE TABLE $tableSymptom (
            $columnSymptomId INTEGER PRIMARY KEY AUTOINCREMENT,
            $columnSymptomName TEXT NOT NULL,
            $columnSymptomSeverity INTEGER NOT NULL,
            $columnSymptomDate TEXT NOT NULL,
            $columnSymptomPeriodId INTEGER,
            FOREIGN KEY ($columnSymptomPeriodId) REFERENCES $tablePeriod ($columnPeriodId)
          )
          ''');

    // 创建排卵表（备孕模式）
    await db.execute('''
          CREATE TABLE $tableOvulation (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            date TEXT NOT NULL,
            basal_temp REAL,
            lh_test_result INTEGER,
            intercourse BOOLEAN,
            note TEXT,
            user_id INTEGER NOT NULL,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId)
          )
          ''');

    // 创建孕期表
    await db.execute('''
          CREATE TABLE $tablePregnancy (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            last_period_date TEXT NOT NULL,
            expected_due_date TEXT NOT NULL,
            current_week INTEGER,
            mood INTEGER,
            energy_level INTEGER,
            weight REAL,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId)
          )
          ''');

    // 创建产检表
    await db.execute('''
          CREATE TABLE $tablePregnancyCheckup (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            pregnancy_id INTEGER NOT NULL,
            checkup_date TEXT NOT NULL,
            doctor TEXT,
            weight REAL,
            blood_pressure TEXT,
            notes TEXT,
            FOREIGN KEY (pregnancy_id) REFERENCES $tablePregnancy (_id)
          )
          ''');

    // 创建宝宝成长表（育儿模式）
    await db.execute('''
          CREATE TABLE $tableBabyGrowth (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            record_date TEXT NOT NULL,
            height REAL,
            weight REAL,
            head_circumference REAL,
            feeding_count INTEGER,
            sleep_hours REAL,
            notes TEXT,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId)
          )
          ''');

    // 创建疫苗表
    await db.execute('''
          CREATE TABLE $tableVaccine (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            vaccine_name TEXT NOT NULL,
            scheduled_date TEXT NOT NULL,
            actual_date TEXT,
            location TEXT,
            notes TEXT,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId)
          )
          ''');

    // 创建食品安全表
    await db.execute('''
          CREATE TABLE $tableFoodSafety (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            food_name TEXT NOT NULL,
            safety_level INTEGER NOT NULL,
            description TEXT,
            category TEXT
          )
          ''');

    // 创建知识库表
    await db.execute('''
          CREATE TABLE $tableKnowledge (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            content TEXT NOT NULL,
            category TEXT NOT NULL,
            sub_category TEXT,
            cover_image TEXT
          )
          ''');

    // 创建照片表
    await db.execute('''
          CREATE TABLE $tablePhoto (
            _id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            photo_path TEXT NOT NULL,
            caption TEXT,
            record_date TEXT NOT NULL,
            FOREIGN KEY (user_id) REFERENCES $tableUser ($columnUserId)
          )
          ''');

    // 插入初始用户数据
    await db.insert(tableUser, {
      columnUserName: '默认用户',
      columnUserMode: 'period',
      columnUserCycle: 28,
      columnUserPeriod: 5,
      columnUserCreatedAt: DateTime.now().toIso8601String(),
      columnUserLastLogin: DateTime.now().toIso8601String()
    });

    // 插入基础食品安全数据
    await _insertBasicFoodSafetyData(db);
    
    // 插入基础知识库数据
    await _insertBasicKnowledgeData(db);
  }

  // 插入基础食品安全数据
  Future _insertBasicFoodSafetyData(Database db) async {
    final foods = [
      {'name': '苹果', 'safety': 3, 'category': '水果', 'desc': '孕期可安全食用'}, 
      {'name': '香蕉', 'safety': 3, 'category': '水果', 'desc': '孕期可安全食用'}, 
      {'name': '西瓜', 'safety': 2, 'category': '水果', 'desc': '适量食用，过量可能导致腹泻'}, 
      {'name': '螃蟹', 'safety': 1, 'category': '海鲜', 'desc': '性寒，孕期应谨慎食用'}, 
      {'name': '人参', 'safety': 1, 'category': '补品', 'desc': '孕期不宜食用，可能导致流产风险'}, 
    ];

    for (var food in foods) {
      await db.insert(tableFoodSafety, {
        'food_name': food['name'],
        'safety_level': food['safety'],
        'category': food['category'],
        'description': food['desc']
      });
    }
  }

  // 插入基础知识库数据
  Future _insertBasicKnowledgeData(Database db) async {
    final knowledgeItems = [
      {
        'title': '经期保健要点',
        'content': '经期应注意保暖，避免生冷食物，保持充足睡眠，适当运动但避免剧烈运动。',
        'category': 'period',
        'sub_category': '保健'
      },
      {
        'title': '排卵期计算方法',
        'content': '排卵期通常在下次月经前14天左右，可通过基础体温监测、排卵试纸等方法辅助判断。',
        'category': 'pregnancy_prep',
        'sub_category': '备孕'
      },
      {
        'title': '孕期第一个月注意事项',
        'content': '确定怀孕后应保持良好作息，开始补充叶酸，避免接触有害物质，及时就医检查。',
        'category': 'pregnancy',
        'sub_category': '早期'
      },
      {
        'title': '新生儿喂养指南',
        'content': '建议纯母乳喂养至少6个月，按需喂养，观察宝宝饥饿信号，注意正确哺乳姿势。',
        'category': 'parenting',
        'sub_category': '喂养'
      }
    ];

    for (var item in knowledgeItems) {
      await db.insert(tableKnowledge, {
        'title': item['title'],
        'content': item['content'],
        'category': item['category'],
        'sub_category': item['sub_category']
      });
    }
  }

  // 获取数据库路径
  Future<String> getDatabasePath() async {
    final documentsDirectory = await getApplicationDocumentsDirectory();
    final path = join(documentsDirectory.path, _databaseName);
    return path;
  }

  // 事务操作
  Future<T> transaction<T>(Future<T> Function(Transaction txn) action) async {
    final db = await database;
    return await db.transaction(action);
  }

  // 通用增删改查方法
  Future<int> insert(String table, Map<String, dynamic> row) async {
    Database db = await instance.database;
    return await db.insert(table, row);
  }

  Future<List<Map<String, dynamic>>> queryAllRows(String table) async {
    Database db = await instance.database;
    return await db.query(table);
  }

  Future<List<Map<String, dynamic>>> queryRows(String table, {Map<String, dynamic>? where, String? orderBy}) async {
    Database db = await instance.database;
    return await db.query(table, 
        where: where?.keys.map((key) => '$key = ?').join(' AND '),
        whereArgs: where?.values.toList(),
        orderBy: orderBy);
  }

  Future<int> update(String table, Map<String, dynamic> row, int id) async {
    Database db = await instance.database;
    return await db.update(table, row, where: '_id = ?', whereArgs: [id]);
  }

  Future<int> updateWhere(String table, Map<String, dynamic> row, Map<String, dynamic> where) async {
    Database db = await instance.database;
    return await db.update(table, row, 
        where: where.keys.map((key) => '$key = ?').join(' AND '),
        whereArgs: where.values.toList());
  }

  Future<int> delete(String table, int id) async {
    Database db = await instance.database;
    return await db.delete(table, where: '_id = ?', whereArgs: [id]);
  }

  Future<int> deleteWhere(String table, Map<String, dynamic> where) async {
    Database db = await instance.database;
    return await db.delete(table, 
        where: where.keys.map((key) => '$key = ?').join(' AND '),
        whereArgs: where.values.toList());
  }

  // 用户管理相关方法
  Future<Map<String, dynamic>?> getUserByEmail(String email) async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(
      tableUser,
      where: '$columnUserEmail = ?',
      whereArgs: [email],
    );
    return maps.isNotEmpty ? maps.first : null;
  }

  Future<int> updateUserMode(int userId, String mode) async {
    return await updateWhere(tableUser, 
        {columnUserMode: mode}, 
        {columnUserId: userId});
  }

  Future<int> updateLastLogin(int userId, DateTime lastLogin) async {
    return await updateWhere(tableUser, 
        {columnUserLastLogin: lastLogin.toIso8601String()}, 
        {columnUserId: userId});
  }

  // 用户设置相关方法
  Future<void> insertUserSettings(int userId, Map<String, String> settings) async {
    final db = await database;
    for (var entry in settings.entries) {
      await db.insert(
        tableUserSettings,
        {
          columnSettingsUserId: userId,
          columnSettingsKey: entry.key,
          columnSettingsValue: entry.value,
        },
        conflictAlgorithm: ConflictAlgorithm.replace,
      );
    }
  }

  Future<Map<String, String>?> getUserSettings(int userId) async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(
      tableUserSettings,
      where: '$columnSettingsUserId = ?',
      whereArgs: [userId],
    );

    if (maps.isEmpty) {
      return null;
    }

    final settings = <String, String>{};
    for (var map in maps) {
      settings[map[columnSettingsKey] as String] = map[columnSettingsValue] as String;
    }
    return settings;
  }

  // 模式相关数据查询方法
  Future<List<Map<String, dynamic>>> getUserPeriods(int userId) async {
    return await queryRows(tablePeriod, 
        where: {columnPeriodUserId: userId}, 
        orderBy: '$columnPeriodStart DESC');
  }

  Future<List<Map<String, dynamic>>> getUserSymptoms(int userId) async {
    // 先获取用户的所有经期ID
    final periods = await getUserPeriods(userId);
    if (periods.isEmpty) return [];
    
    final periodIds = periods.map((p) => p[columnPeriodId]).toList();
    final db = await database;
    return await db.query(
      tableSymptom,
      where: '$columnSymptomPeriodId IN (${List.filled(periodIds.length, '?').join(', ')})',
      whereArgs: periodIds,
      orderBy: '$columnSymptomDate DESC',
    );
  }

  // 跨模式数据获取方法
  Future<Map<String, dynamic>?> getPregnancyInfo(int userId) async {
    final db = await database;
    final List<Map<String, dynamic>> maps = await db.query(
      tablePregnancy,
      where: 'user_id = ?',
      whereArgs: [userId],
    );
    return maps.isNotEmpty ? maps.first : null;
  }

  Future<List<Map<String, dynamic>>> getUserBabies(int userId) async {
    return await queryRows(tableBabyInfo, 
        where: {'user_id': userId}, 
        orderBy: 'birth_date DESC');
  }

  Future<List<Map<String, dynamic>>> getBabyGrowthRecords(int babyId) async {
    return await queryRows(tableBabyGrowth, 
        where: {'_id': babyId}, 
        orderBy: 'record_date DESC');
  }

  // 删除用户及其所有数据
  Future<int> deleteUserAndAllData(int userId) async {
    final db = await database;
    // 使用事务确保数据一致性
    return await db.transaction((txn) async {
      // 删除用户表记录（由于外键约束，相关数据会自动删除）
      return await txn.delete(tableUser, where: '$columnUserId = ?', whereArgs: [userId]);
    });
  }

  // 数据库升级方法 - 移除未使用的方法
  // Future _onUpgrade(Database db, int oldVersion, int newVersion) async {
  //   if (oldVersion < 2) {
  //     // 版本2：添加用户设置表和跨模式支持的新表
  //     await db.execute('''
  //         CREATE TABLE $tableUserSettings (
  //           $columnSettingsId INTEGER PRIMARY KEY AUTOINCREMENT,
  //           $columnSettingsUserId INTEGER NOT NULL,
  //           $columnSettingsKey TEXT NOT NULL,
  //           $columnSettingsValue TEXT NOT NULL,
  //           FOREIGN KEY ($columnSettingsUserId) REFERENCES $tableUser ($columnUserId) ON DELETE CASCADE,
  //           UNIQUE ($columnSettingsUserId, $columnSettingsKey)
  //         )
  //         ''');
  //         
  //     // 添加用户表新字段
  //     try {
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserEmail TEXT UNIQUE');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserPasswordHash TEXT');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserPhone TEXT');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserDOB TEXT');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserHeight INTEGER');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserWeight INTEGER');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserBloodType TEXT');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserCreatedAt TEXT');
  //       await db.execute('ALTER TABLE $tableUser ADD COLUMN $columnUserLastLogin TEXT');
  //     } catch (e) {
  //       // 如果字段已存在，忽略错误
  //       print('更新用户表字段时出错: $e');
  //     }
  //     
  //     // 更新默认用户的创建时间和最后登录时间
  //     final now = DateTime.now().toIso8601String();
  //     await db.update(tableUser, 
  //         {columnUserCreatedAt: now, columnUserLastLogin: now}, 
  //         where: '$columnUserId = 1');
  //   }
  // }

  // 导出数据库用于备份
  Future<String> exportDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String dbPath = join(documentsDirectory.path, _databaseName);
    String backupPath = join(documentsDirectory.path, 'moonmate_backup.db');
    
    File dbFile = File(dbPath);
    await dbFile.copy(backupPath);
    
    return backupPath;
  }

  // 导入数据库用于恢复
  Future<bool> importDatabase(String backupPath) async {
    try {
      Directory documentsDirectory = await getApplicationDocumentsDirectory();
      String dbPath = join(documentsDirectory.path, _databaseName);
      
      File backupFile = File(backupPath);
      if (await backupFile.exists()) {
        // 关闭当前数据库连接
        if (_database != null) {
          await _database!.close();
          _database = null;
        }
        
        // 复制备份文件
        await backupFile.copy(dbPath);
        
        // 重新打开数据库
        await instance.database;
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('导入数据库失败: $e');
      return false;
    }
  }
}